package interface_layer;

import java.io.InputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import processing_layer.User;

import database_layer.Common;
import database_layer.QueryDispatcher;

/**
 * This servlet is in charge of returning the user image to the requesting
 * JSP for display
 */
public class UserImage extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserImage()
    {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
	{
		try
		{
			String requestedUser = request.getParameter("user");
			String username = (String)request.getSession().getAttribute("username");
			
			if (null == username)
			{
				ErrorHandler.parseForErrors(Common.UNAUTHORIZED_OPERATION, response, null);
				return;
			}
			
			if (null == requestedUser)
			{
				ErrorHandler.parseForErrors(Common.BAD_PARAMETERS, response, null);
				return;
			}
			
			else
			{
				try
				{
					User userDetails = QueryDispatcher.getUserDetails(requestedUser);
					if (null == userDetails)
					{
						ErrorHandler.parseForErrors(Common.INTERNAL_DB_ERROR, response, null);
						return;
					}
					
					if (null == userDetails.username)
					{
						ErrorHandler.parseForErrors(Common.ENTRY_DOESNT_EXIST, response, null);
						return;					
					}
					
					if (null != userDetails.photo)
					{
						response.setContentType("image/jpeg");
						InputStream in = userDetails.photo.getBinaryStream();
						int length = (int) userDetails.photo.length();
						int bufferSize = 1024;
					      byte[] buffer = new byte[bufferSize];
					      ServletOutputStream out = response.getOutputStream();
					      while ((length = in.read(buffer)) != -1) {
					        out.write(buffer, 0, length);
					      }
					      in.close();
					      out.close();
					}
					else
					{
						response.sendRedirect("images/no-image.gif");
					}
					
				}
				catch (Exception e)
				{
					ErrorHandler.parseForErrors(Common.INTERNAL_DB_ERROR, response, null);
				}
			}
		}
		catch (Exception e)
		{
			System.out.println("Exception is : " + e.getLocalizedMessage());
			ErrorHandler.parseForErrors(Common.INTERNAL_ERROR, response, null);
		}
	}

}
